package com.hgy.carsb.service;

import com.hgy.carsb.entity.EveryMonthData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

@Service
public class TotalTrendService {
    @Autowired
    private InfoService infoService;

    public EveryMonthData getSum(int year, String code1, String code2, String prefix){
        EveryMonthData everyMonthData = new EveryMonthData();
        for (int i=1; i<=12; i++){
            String sum = infoService.getRatio(year, i, code1, code2, prefix);
            everyMonthData.set(sum, i);
        }
        return everyMonthData;
    }

    public EveryMonthData getMonth(int year, String code1, String code2, String prefix){
        EveryMonthData ans = new EveryMonthData();
        String sum1 = infoService.getRatio(year, 1, code1, code2, prefix);
        String sum2 = infoService.getRatio(year-1, 12, code1, code2, prefix);
        ans.setJanuary(getRatio(sum1, sum2));
        for (int i=2; i<=12; i++){
            sum1 = infoService.getRatio(year, i, code1, code2, prefix);
            sum2 = infoService.getRatio(year, i-1, code1, code2, prefix);
            ans.set(getRatio(sum1, sum2), i);
        }
        return ans;
    }

    public EveryMonthData getYear(int year, String code1, String code2, String prefix){
        EveryMonthData ans = new EveryMonthData();
        for (int i=1; i<=12; i++){
            String sum1 = infoService.getRatio(year, i, code1, code2, prefix);
            String sum2 = infoService.getRatio(year-1, i, code1, code2, prefix);
            ans.set(getRatio(sum1, sum2), i);
        }
        return ans;
    }

    public String getRatio(String sum1, String sum2){
        BigDecimal s1 = new BigDecimal(sum1);
        BigDecimal s2 = new BigDecimal(sum2);
        s1 = s1.subtract(s2);
        if (s2.compareTo(new BigDecimal(0))==0){
            s1 = new BigDecimal(0);
        }else {
            s1 = s1.multiply(new BigDecimal(100)).divide(s2, 2,BigDecimal.ROUND_HALF_UP);
        }
        return s1.toString();
    }
}
